package rpc.http.client;

import rpc.common.MyInvocation;

import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;

/**
 * 自定义Http客户端
 */
public class MyHttpClient {
    /**
     * 发送请求
     */
    public static String send(String hostname, Integer port, MyInvocation myInvocation) {
        try {
            //构建URI
            URI uri = new URI("http://" + hostname + ":" + port + "/");
            //获取URL
            URL url = uri.toURL();
            //开启Http连接
            HttpURLConnection httpURLconnection = (HttpURLConnection) url.openConnection();
            //设置请求类型
            httpURLconnection.setRequestMethod("POST");
            //设置是否可以输出
            httpURLconnection.setDoOutput(true);

            //从Http连接获取输出流
            OutputStream outputStream = httpURLconnection.getOutputStream();
            //构建对象输出流
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            //写入对象至缓冲区
            objectOutputStream.writeObject(myInvocation);
            //将缓冲区内容刷新到到底层流
            objectOutputStream.flush();
            //关闭对象输出流
            objectOutputStream.close();

            //从Http连接获取输入流
            InputStream inputStream = httpURLconnection.getInputStream();
            byte[] bytes = new byte[inputStream.available()];
            //写入内容至字节数组
            inputStream.read(bytes);
            //关闭输入流
            inputStream.close();

            //关闭Http连接
            httpURLconnection.disconnect();
            return new String(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
